﻿using System;
using System.Web.Mvc;
using Tss.MagicWeb.Domain.Infrastructure.Auth;
using Tss.MagicWeb.Kernel;

namespace Tss.MagicWeb.Filters
{
    class AuthenticationFilter : AuthorizeAttribute
    {
        private bool _isRequired = true;

        public AuthenticationFilter()
        {

        }

        public AuthenticationFilter(bool isRequired)
        {
            _isRequired = isRequired;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var controller = (Controllers.Controller)filterContext.Controller;

            if (!_isRequired)
            {
                return;
            }

            if (controller.Name == "Default")
            {
                string url = controller.Url.Action(Constants.Mvc.Action.Login, Constants.Mvc.Controller.Account);
                filterContext.Result = new RedirectResult(url);
            }

            if (!LoginUtils.CurrentUser.IsLogged)
            {
                string url = controller.Url.Action(Constants.Mvc.Action.Login, Constants.Mvc.Controller.Account);
                filterContext.Result = new RedirectResult(url);
            }
        }
    }

}